package com.qskj.springsecurity.single.filter;

import com.qskj.springsecurity.single.exception.VerificationCodeException;
import com.qskj.springsecurity.single.handler.FailtureHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author shikf
 * @version 1.0     2021-02-04 10:21
 */
//@Component
public class VerificationCodeFilter extends OncePerRequestFilter {

    private AuthenticationFailureHandler failureHandler = new FailtureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (!"/login".equals(requestURI)) {
            filterChain.doFilter(request, response);
        } else {
            try {
                verificationCode(request);
                filterChain.doFilter(request, response);
            } catch (VerificationCodeException e) {
                failureHandler.onAuthenticationFailure(request,response,e);
            }
        }
    }

    private void verificationCode(HttpServletRequest request) {

        String kaptcha = request.getParameter("kaptcha");
        Object kaptchaObj = request.getSession().getAttribute("kaptcha");
        String saveKaptcha = null;
        if (kaptchaObj!= null) {
            saveKaptcha = (String) kaptchaObj;
            request.getSession().removeAttribute("kaptcha");
        } else {
            throw new VerificationCodeException();
        }
        if (!StringUtils.equals(saveKaptcha, kaptcha)) {
            throw new VerificationCodeException();
        }
    }
}
